package com.shu.project.service.impl;

import com.shu.framework.constant.UserConstants;
import com.shu.framework.enums.CodeMsg;
import com.shu.framework.exception.user.UserException;
import com.shu.framework.redis.RedisService;
import com.shu.framework.redis.SessionKey;
import com.shu.framework.utils.MD5Util;
import com.shu.framework.utils.StringUtils;
import com.shu.framework.utils.UUIDUtil;
import com.shu.project.dao.UserDao;
import com.shu.project.model.User;
import com.shu.project.service.IUserService;
import com.shu.project.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service(value = "userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    RedisService redisService;
    @Override
    public User queryUserById(Long id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public boolean updateUserInfo(User user) {

        return userDao.updateByPrimaryKey(user)>0?true:false;
    }

    @Override
    public User selectUserByEmail(String email) {
        return userDao.selectUserByEmail(email);
    }

    @Override
    public User selectUserByPhoneNo(String phoneNo) {
        return userDao.selectUserByPhoneNo(phoneNo);
    }

    @Override
    public User selectUserByNickName(String nickName) {
        return userDao.selectUserByNickName(nickName);
    }

    @Override
    public boolean login(HttpServletResponse response,LoginVo loginVo) {
        //查询用户信息
        User user = userDao.selectUserByPhoneNo(loginVo.getMobile());
        if (StringUtils.isNull(user)){
            throw new UserException(CodeMsg.PHONENO_NOT_EXITS);
        }
        //密码验证
        String salt = user.getSalt();
        String dbpass = user.getPassword();
        String formPass = MD5Util.formPassToDBPass(loginVo.getPassword(), salt);
        if (!dbpass.equals(formPass)){
            throw new UserException(CodeMsg.PASSWORD_ERROR);
        }
        //生成cookile
        String token= UUIDUtil.uuid();
        //添加cookie
        addCookie(response,user, token);
        return true;
    }

    @Override
    public User getByToken(HttpServletResponse response,String token) {
        if (StringUtils.isEmpty(token)){
            return null;
        }
        User user = redisService.get(SessionKey.token, token, User.class);
        if (!StringUtils.isNull(user)) {
            //延长有效期
            addCookie(response, user,token);
        }
        return user;
    }
    private void addCookie(HttpServletResponse response, User user, String token){

        //放入redis中
        redisService.set(SessionKey.token,token,user);
        Cookie cookie = new Cookie(UserConstants.COOKIE_NAME,token);
        cookie.setMaxAge(SessionKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
